package com.storyroad.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.storyroad.responseClasses.Results;
import com.storyroad.utils.DBConnection;
import com.storyroad.utils.TableNames;
import com.storyroad.utils.Utilities;

/**
 * Servlet implementation class GetKeywords
 */
public class GetKeywords extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetKeywords() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * Finds the usernames, tags and story titles in the system which contain the specified keyword. An instance of
	 * {@link com.storyroad.responseClasses.Results} object which contains the list of matched content is returned to the
	 * front-end.
	 * @param request HttpServletRequest object that contains data coming from front-end
	 * @param response HttpServletResponse object that contains data which is prepared after processing the incoming data
     * @throws IOException
     */
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		PrintWriter out = response.getWriter();
		Connection conn = new DBConnection().connect();
		ArrayList<String> result = new ArrayList<String>();
		String filter = request.getParameter("query");

		result.addAll(Utilities.autoCompleteFilter(conn, TableNames.USERS_TABLE, "username", filter));
		result.addAll(Utilities.autoCompleteFilter(conn, TableNames.STORIES_TABLE, "title", filter));
		result.addAll(Utilities.autoCompleteFilter(conn, TableNames.TAGS_TABLE, "tag", filter));

		Results keywords = new Results();
		keywords.setResults(result);
		JSONObject jsonObject = new JSONObject(keywords);
		String allKeywordsJsonString = jsonObject.toString();
		out.print(allKeywordsJsonString);
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
